import requests
import json
import public_config

from flask import g, current_app
from apps.project.models.version import Version
from apps.project.settings import config
from apps.auth.models.users import User
from apps.project.models.issue import Issue
from apps.project.models.project import Project
from enum import Enum
from library.api.security import Validation


class ZenTaoBusiness(object):
    zt_base_url = config.ZENTAO_BASE_URL
    zt_user = config.ZENTAO_USER
    zt_password = config.ZENTAO_PASSWORD
    zt_headers = config.HEADERS
    config = config
    m = config.INTERFACE_URL.get('m')
    f = config.INTERFACE_URL.get('f')
    t = config.INTERFACE_URL.get('t')
    res_param = config.RESPONSE_PARAM
    
    @classmethod
    def get_session(cls):
        """获取会话
        :return:
        """
        r_session = requests.session()
        return r_session
    
    @classmethod
    def _query_params(cls, m, f, session_name, session_id):
        return {'m': m, 'f': f, 't': 'json', session_name: session_id}
    
    @classmethod
    def _query_params_new(cls, m, f, t, dy_params={}):
        params = dict({'m': m, 'f': f, 't': t})
        for x in dy_params.keys():
            params[x] = dy_params[x]
        return params
    
    @classmethod
    def zt_session(cls, r_session):
        """
        :return:
        """
        if not r_session:
            r_session = requests.session()
            cls.zt_new_login(r_session, g.userid)
        return r_session
    
    @classmethod
    def zt_login(cls):
        session_params = {'m': 'api', 'f': 'getSessionID', 't': 'json'}
        s_response = requests.get(cls.zt_base_url, session_params)
        if s_response.status_code != 200:
            return dict()
        login_json_data = json.loads(s_response.json()['data'])
        s_name = login_json_data['sessionName']
        s_id = login_json_data['sessionID']
        login_params = cls.__query_params('user', 'login', s_name, s_id)
        login_params['account'] = cls.zt_user
        login_params['password'] = cls.zt_password
        login_response = requests.get(cls.zt_base_url, params=login_params)
        if login_response.status_code != 200 or login_response.json()['status'] != 'success':
            return dict()
        return dict(name=s_name, id=s_id)
    
    @classmethod
    def zt_new_login(cls, r_session, user_id, name=None, password=None):
        """登陆禅道
        :param r_session:会话
        :param user_id:用户id
        :param name:账号
        :param password:密码
        :return:
        """
        # 查询当前用户的数据
        user_name = ''
        user_password = ''
        if user_id != 0:
            result_user = User.query.filter(User.id == user_id).first()
            if result_user.ext:
                user_name = result_user.name
                user_password = Validation.aes_decrypt(result_user.ext)
        else:
            if name and password:
                user_name = name
                user_password = password
            else:
                user_name = cls.zt_user
                user_password = cls.zt_password
        
        login_params = cls._query_params_new('user', 'login', 'json')
        response_url = r_session.get(cls.zt_base_url, params=login_params).url
        
        headers = cls.zt_headers
        headers['Referer'] = response_url
        
        body = {
            'account': user_name,
            'password': user_password,
            'keepLogin[]': 'on',
            'referer': '/zentao/',
            'verifyRand': 2035112972
        }
        
        login_response = r_session.post(url=response_url, data=body, headers=headers)
        if login_response.status_code != 200 or login_response.json()['status'] != 'success':
            raise Exception('账号:{},密码:{}登录失败，请检查'.format(user_name, user_password))
        return login_response.json()
    
    @classmethod
    def zt_bug(cls, project_id, session_id, action):
        bug_params = cls.__query_params('bug', 'browse', 'zentaosid', session_id)
        bug_params['productID'] = project_id
        bug_params['branch'] = 0
        bug_params['browseType'] = action
        b_response = requests.get(cls.zt_base_url, bug_params)
        if b_response.status_code == 200:
            bug_info = json.loads(b_response.json()['data'])
            return dict(name=bug_info['productName'],
                        size=bug_info['pager']['recTotal'])
        return dict()
    
    @classmethod
    def zt_requirement(cls, project_id, session_id):
        requirement_params = cls.__query_params('product', 'browse', 'zentaosid', session_id)
        requirement_params['productID'] = project_id
        requirement_params['branch'] = 0
        requirement_params['browseType'] = all
        r_response = requests.get(cls.zt_base_url, requirement_params)
        if r_response.status_code == 200:
            return r_response.json()['data']
        return dict()
    
    @classmethod
    def zt_test_case(cls, project_id, session_id):
        case_params = {'m': 'testcase', 'f': 'browse', 't': 'json', 'productID': project_id,
                       'branch': 0, 'browseType': 'all', 'zentaosid': session_id}
        c_response = requests.get(cls.zt_base_url, case_params)
        if c_response.status_code == 200:
            return c_response.json()['data']
        return dict()
    
    @classmethod
    def get_zt_version(cls, zt_product_id):
        r_session = requests.session()  # 保持会话
        status = cls.zt_new_login(r_session, 0)['status']
        if status != 'success':
            raise Exception('禅道登录失败，请检查账号')
        request_params = cls._query_params_new(m="product", f="project", t="json",
                                                dy_params={'status': 'all',
                                                           'productID': zt_product_id})
        data = r_session.get(cls.zt_base_url, params=request_params).json()
        if data['status'] == 'success':
            version = json.loads(data['data'])['projectStats']
            return [{'id': item['id'], 'name': item['name'], 'operator': item['openedBy'],
                     'desc': item['desc'],
                     'begin': item['begin'], 'end': item['end']}
                    for item in version if item['status'] != 'closed']
        return []
    
    @classmethod
    def zt_product(cls, session_id):
        p_params = cls.__query_params('product', 'all', 'zentaosid', session_id)
        p_params['productID'] = 0
        p_params['line'] = 0
        p_params['status'] = 'noclosed'
        p_params['orderBy'] = 'order_desc'
        p_params['recTotal'] = 20
        p_params['recPerPage'] = 20
        p_params['pageID'] = 1
        p_response = requests.get(cls.zt_base_url, p_params)
        if p_response.status_code == 200:
            list_product = json.loads(p_response.json()['data'])['productStats']
            return [{'id': product['id'], 'name': product['name']} for product in list_product]
        return []
    
    @classmethod
    def get_bug_id(cls, r_session, bug_list_url):
        # 获取bug列表的url
        url = 'm=bug&f=browse&productID=23&branch=0&browseType=unclosed&param=0&orderBy=id_desc&recPerPage=20'
        bug_list_url = cls.zt_base_url + str(bug_list_url)
        headers = cls.zt_headers
        headers['Referer'] = bug_list_url
        bug_id_response = r_session.get(url=bug_list_url, headers=headers)
        if bug_id_response.status_code == 200:
            return []
        return []
    
    @classmethod
    def get_bug_modules(cls, zt_product_id):
        r_session = requests.session()  # 保持会话
        status = cls.zt_new_login(r_session, 0)['status']
        if status != 'success':
            raise Exception('禅道登录失败，请检查账号')
        query_params = cls._query_params_new(m='tree', f='browse', t='json',
                                              dy_params={'productID': zt_product_id,
                                                         'type': 'story',
                                                         'currentModuleID': 0})
        response = r_session.get(cls.zt_base_url, params=query_params).json()
        if response['status'] == 'success':
            return [{'id': int(x['id']), 'name': x['name']} for x in
                    json.loads(response['data'])['tree']]
        else:
            raise Exception('查询出现错误了！')
    
    @classmethod
    def sync_issue(cls, project_id, module_id, version, handler, issue_type,
                   chance, level, priority, title, description):
        """
            # 禅道创建bug后
            :return bug_id
        """
        # 指派人
        handle_user = User.query.filter(User.id == handler).first()
        assigned_to = handle_user.name if handle_user.name else None
        
        if g.userid:
            user_id = g.userid
        else:
            raise Exception('用户id不存在')
        
        r_session = requests.session()
        cls.zt_new_login(r_session, user_id)
        
        # 同步bug 获取列表url链接
        bug_id = cls.zt_create_bug(r_session, project_id, module_id, version,
                                   assigned_to, issue_type,
                                   chance, level, priority, title, description)
        if not bug_id:
            return 0
        return bug_id
    
    @classmethod
    def zt_create_bug(cls, r_session, project_id, module_id, version, assigned_to, issue_type,
                      chance, level, priority, title, description):
        """
        禅道创建bug
        :return: None
        """
        # 获取禅道product_id
        result_project = Project.query.filter(Project.id == project_id).first()
        if result_project.zt_product == 0:
            raise Exception('找不到项目id')
        
        version_data = Version.query.filter(Version.id == version).first()
        if not version_data:
            raise Exception('issue迭代版本不能为空')
        
        query_params = cls._query_params_new(m='bug', f='create', t='json',
                                              dy_params={'productID': result_project.zt_product,
                                                         'branch': 0,
                                                         'extras': 'moduleID=0'})
        headers = cls.zt_headers
        chance = public_config.ISSUE_CONFIG['chance'][chance]
        
        style = '<h1><span style="font-size:14px;font-weight:400;color:#E53333;">出现机率:{}</span></h1>\n{}'
        content = style.format(chance, description)
        zt_type = 'requirebug'
        for i in TypeEnums:
            if i.id == issue_type:
                zt_type = i.desc
                break
        bug_body = {
            'product': result_project.zt_product,  # 项目id 接口问题
            'title': title,  # 标题
            'type': zt_type,  # bug类型
            'project': version_data.zt_version_id,
            'openedBuild[]': 'trunk',  # 影响版本 'trunk'
            'status': 'active',  # 状态：激活
            'module': module_id,  # 主模块
            'assignedTo': assigned_to,  # 指派人
            'steps': content,  # 内容
            'severity': level,  # 严重等级
            'pri': priority,  # 优先级
            'uid': '5e8492c6afe8d',  # uid写死
        }
        
        bug_response = r_session.post(url=cls.zt_base_url,
                                      params=query_params,
                                      data=bug_body,
                                      headers=headers)
        # current_app.logger.info(bug_response)
        if bug_response.status_code == 200 and bug_response.json()['locate']:
            bug_list = r_session.get(
                cls.zt_base_url + "?" + bug_response.json()['locate'].split('?')[1])
            for ie in json.loads(bug_list.json()['data'])['bugs']:
                if ie['title'] == title:
                    return ie['id']
        return None
    
    @classmethod
    def zt_close_bug(cls, r_session, bug_id, *close_comment):
        """
        关闭bug
        :return: close_bug_response
        """
        comment = close_comment if close_comment else None
        
        close_bug_param = {'bugId': int(bug_id)}
        close_param = cls._query_params_new('bug', 'close', 'json', close_bug_param)
        base_url = requests.get(cls.zt_base_url, close_param).url
        headers = cls.zt_headers
        headers['Referer'] = base_url
        close_param = {
            'm': 'bug',
            'f': 'close',
            'bugID': bug_id,
            'onlybody': 'yes'
        }
        
        bug_body = {
            'status': 'closed',
            'comment': comment,
            'uid': '5e999b2578bad'
        }
        
        close_bug_response = r_session.post(url=cls.zt_base_url,
                                            params=close_param,
                                            data=bug_body,
                                            headers=headers)
        if close_bug_response.status_code == 200:
            return close_bug_response
        return None
    
    @classmethod
    def activate_bug(cls, r_session, bug_id):
        """激活bug
        :return:
        """
        dy_params = {
            'bugID': int(bug_id)
        }
        activate_url = cls._query_params_new('bug', 'activate', 'json', dy_params)
        base_url = requests.get(cls.zt_base_url, activate_url).url
        headers = cls.zt_headers
        headers['Referer'] = base_url
        
        activate_body_param = {
            'assignedTo': 'hepengchong',
            'status': 'active',
            'openedBuild': 'trunk',
            'comment': '',
            'labels': '',
            'files': 'application/octet-stream',
            'uid': '5e982e0812f7f'
        }
        
        get_param = {
            'm': 'bug',
            'f': 'activate',
            'bugID': bug_id,
            'onlybody': 'yes'
        }
        
        base_response = r_session.post(url=cls.zt_base_url,
                                       params=get_param,
                                       data=activate_body_param,
                                       headers=headers)
        if base_response.status_code == 200:
            return 0
        raise Exception('激活bug失败')
    
    @classmethod
    def issue_status(cls, before_status, mstatus, id):
        """同步禅道bug状态-激活、关闭
        :return:
        """
        if not id:
            raise Exception('issue_id不存在')
        
        if not g.userid:
            raise Exception('当前用户不存在')
        else:
            user_id = g.userid
        
        r_session = requests.session()
        bug_id = int(Issue.query.filter(Issue.id == id).first().zt_bug_id)
        # 如果禅道有bug_id管理==关联issue
        if bug_id:
            # cls.zt_new_login(r_session, user_id)
            cls.zt_new_login(r_session, user_id)
        else:
            return 0
        # 处理状态
        # 1:代办
        # 2:已修复-定时任务
        # 4:已关闭
        # 5:删除
        
        # 如果之前状态为激活->只能走关闭bug或者已解决
        if before_status == 1 or before_status == 2:
            if mstatus == 4:
                cls.zt_close_bug(r_session, bug_id)
                return 0
            if mstatus == 3:
                cls.resolved_bug(r_session, bug_id)
                return 0
            else:
                raise Exception('issue流转状态有误')
        
        # 如果状态为已修复->代办为激活
        if before_status == 3:
            if mstatus == 1 or mstatus == 2:
                cls.activate_bug(r_session, bug_id)
                return 0
            # ->关闭
            elif mstatus == 4:
                cls.zt_close_bug(r_session, bug_id)
                return 0
            else:
                raise Exception('issue流转状态有误')
        else:
            return 0
    
    @classmethod
    def resolved_bug(cls, r_session, bug_id):
        """解决bug
        :return:
        """
        bug_params = cls._query_params_new('bug', 'resolve', 'json',
                                            dy_params={'bug_id': bug_id, 'onlybody': 'yes'})
        response_url = requests.get(cls.zt_base_url, bug_params).url
        headers = cls.zt_headers
        headers['Referer'] = response_url
        
        data = {
            'resolution': 'fixed',
            'duplicateBug': '',
            'buildProject': '',
            'resolvedBuild': 'trunk',
            'buildName': '',
            'resolvedDate': '2020-05-30 16:20:17',
            'assignedTo': 'hepengchong',
            'status': 'resolved',
            'labels[]': '',
            # 'files[]': '(binary)',
            # 'comment': 'comment',
            'uid': '5ed20e9516904'
        }
        params = {
            'm': 'bug',
            'f': 'resolve',
            'bugID': bug_id,
            'onlybody': 'yes'
        }
        base_response = r_session.post(url=cls.zt_base_url,
                                       headers=headers,
                                       params=params,
                                       data=data)
        if base_response.status_code == 200:
            return []
        return []
    
    @classmethod
    def find_zt_status(cls, bug_ids):
        """
        :param bug_ids:
        :return:bug_dict = {
                            'bug_id': bug_list,
                            'issue_status': issue_status
                        }
        """
        # 使用超管登陆
        r_session = requests.session()
        ZenTaoBusiness.zt_new_login(r_session, 0)
        headers = cls.zt_headers
        bug_list = []
        # 遍历bug_id 去禅道查bug状态
        for bug_id in bug_ids:
            dy_params = {'bugId': bug_id}
            url_param = cls._query_params_new('bug', 'view', 'json', dy_params)
            r_url = requests.get(cls.zt_base_url, url_param).url
            headers['Referer'] = r_url
            res = r_session.get(url=r_url,
                                headers=headers)
            
            if res.status_code == 200:
                content = res.content.decode()
                json_content = json.loads(content)
                result = json.loads(json_content['data'])
                is_deleted = result['bug']['deleted']
                # 如果bug已删除,todo 状态返回
                if is_deleted == '1':
                    bug_list.append({'bug_id': bug_id, 'issue_status': 'deleted'})
                    continue
                bug_status = result['bug']['status']
                # 如果zt_bug状态不为active,加入list
                if bug_status != cls.config.ZENTAO_ACTIVE:
                    issue_status = bug_status
                    bug_list.append({'bug_id': bug_id, 'issue_status': issue_status})
        if not bug_list:
            return None
        
        current_app.logger.info('bug_list: {}'.format(bug_list))
        return bug_list
    
    @classmethod
    def get_iteration_user(cls, r_session, project_id):
        """获取迭代人员
        :param r_session:
        :param project_id:迭代id
        :return:
        """
        prefix_param = cls._query_params_new('project', 'team', 'json',
                                              dy_params={'projectID': project_id})
        r_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = r_url
        res = r_session.get(url=cls.zt_base_url, params=prefix_param, headers=headers)
        if res.status_code == 200:
            user_data = json.loads(json.loads(res.text).get('data')).get('teamMembers')
            # 取出value
            base_user = list(dict(user_data).values())
            user = [{'id': user.get('id'), 'account': user.get('account'),
                     "role": user.get('role'), 'realname': user.get('realname')}
                    for user in base_user]
            return user
        return None
    
    @classmethod
    def get_case_library(cls, r_session=None):
        """获取所有用例库
        :param r_session: 保持会话
        :return:dict{1:'a用例库'}
        """
        try:
            if not r_session:
                r_session = requests.session()
                cls.zt_new_login(r_session, 0)
            # 获取用例库接口param-objectID值固定
            prefix_param = cls._query_params_new('caselib', 'ajaxGetDropMenu', 'json',
                                                  dy_params={'module': 'caselib',
                                                             'method': 'browse',
                                                             'objectID': 17})
            url = requests.get(cls.zt_base_url, prefix_param).url
            headers = cls.zt_headers
            headers['Referer'] = url
            # 请求获取用例库接口
            s_data = r_session.get(url=cls.zt_base_url, params=prefix_param, headers=headers)
            if s_data.status_code == 200:
                s_data = json.loads(s_data.text)
                all_library = json.loads(s_data.get('data')).get('libraries')
                return all_library
            return None
        except Exception as e:
            current_app.logger.error(str(e))
            return None
    
    @classmethod
    def according_name_find_ib(cls, library_name, r_session=None):
        """获取指定名字的用例库id
        :return:
        """
        try:
            if not r_session:
                r_session = requests.session()
                cls.zt_new_login(r_session, g.userid)
            library = cls.get_case_library(r_session)
            for l_id in library:
                if library[l_id].find(library_name) != -1:
                    return l_id
            return None
        except Exception as e:
            current_app.logger.error(str(e))
            return None
    
    @classmethod
    def according_module_name_find_id(cls, module_name, all_module, r_session, lib_id):
        """获取指定名字或许模块id
        :param module_name: 模块名称
        :param all_module: 所有模块
        :param lib_id: 所有模块
        :param r_session:
        :return:
        """
        try:
            if not r_session:
                r_session = requests.session()
                cls.zt_new_login(r_session, g.userid)
            if all_module is None:
                all_module = cls.get_all_module_id(lib_id, r_session)
            for m_id in all_module:
                if all_module[m_id] == module_name:
                    return m_id
            return None
        except Exception as e:
            current_app.logger.error(str(e))
    
    @classmethod
    def find_modules(cls, r_session, module_name, lid):
        """添加模块
        :return:
        """
        # 拆解模块
        all_modules_name = module_name.split('/')[1:]
        module_id = i = 0
        while True:
            # 获取模块下所有子模块
            all_modules = cls.get_zt_modules(r_session, lid, module_id)
            if i >= len(all_modules_name):
                return module_id
            # 查询模块是否存在，不存在则添加
            if all_modules.get(all_modules_name[i]) is None:
                # 添加模块
                cls.add_lid_modules(r_session, all_modules_name[i], lid, module_id)
            else:
                module_id = all_modules.get(all_modules_name[i])
                i += 1
    
    @classmethod
    def add_lid_modules(cls, r_session, name, lid, modules_id=None):
        """添加用例库模块
        :param r_session:
        :param name: 模块名称
        :param lid: 用例库id
        :param modules_id: 模块id
        :return:
        """
        if modules_id:
            prefix_param = cls._query_params_new('tree', 'manageChild', 'json',
                                                  dy_params={'root': lid, 'viewType': 'caselib',
                                                             'moduleID': modules_id, 'branch': 0})
        else:
            prefix_param = cls._query_params_new('tree', 'manageChild', 'json',
                                                  dy_params={'root': lid, 'viewType': 'caselib'})
        
        add_modules_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = add_modules_url
        
        add_modules_data = {
            'modules[]': name,
            'shorts[]': '',
            'parentModuleID': modules_id
        }
        res = r_session.post(url=cls.zt_base_url, headers=headers, params=prefix_param,
                             data=add_modules_data)
        if res.status_code == 200:
            return res.text
    
    @classmethod
    def new_zt_case_library_sync(cls, r_session, case_data, zt_data):
        """禅道用例库同步用例-同步
        :return:
        """
        try:
            res_case = r_session.post(url=cls.zt_base_url, data=case_data,
                                      params=zt_data.get('prefix_param'),
                                      headers=zt_data.get('headers'))
            if res_case.status_code == 200:
                if res_case.text.find("alert") != -1:
                    text = res_case.text.split("alert('")[1].split("')\n")[0]
                    case_id = res_case.text.split('caseID=')[1].split('\'')[0]
                    err = {'text: ': text, 'case_id: ': case_id}
                    current_app.logger.info(err)
        except Exception as e:
            current_app.logger.error(str(e))
    
    @classmethod
    def excel_zt_case(cls, case_data):
        """批量导入excel用例
        :param case_data:
        :return:
        """
        try:
            r_session = requests.session()
            ZenTaoBusiness.zt_new_login(r_session, g.userid)
            for index, data in enumerate(case_data, 1):
                ZenTaoBusiness.zt_case_sync(r_session, data)
                current_app.logger.info('num:{} 用例标题:{}'.format(index, data.get('title')))
            return 0, ''
        except Exception as e:
            current_app.logger.error(str(e))
            return 1, str(e)
    
    @classmethod
    def zt_case_sync(cls, r_session, data):
        """禅道用例同步
        :param r_session:会话
        :param data:用例数据
        :return:
        """
        prefix_params = cls._query_params_new('testcase', 'create', 'json',
                                               dy_params={'productID': data.get('product'),
                                                          'branch': 0,
                                                          'moduleID': data.get('module')})
        params_url = requests.get(cls.zt_base_url, prefix_params).url
        headers = cls.zt_headers
        headers['Referer'] = params_url
        res_case = r_session.post(url=cls.zt_base_url, data=data,
                                  params=prefix_params,
                                  headers=headers)
        if res_case.status_code == 200:
            return '成功'
        return res_case.text
    
    @classmethod
    def get_zt_modules(cls, r_session, lid, modules_id):
        """获取禅道用例库的一级模块名
        :return:
        """
        if modules_id:
            prefix_param = cls._query_params_new('tree', 'browse', 'json',
                                                  dy_params={'rootID': lid,
                                                             'viewType': 'caselib',
                                                             'moduleID': modules_id,
                                                             'branch': 0})
        else:
            prefix_param = cls._query_params_new('tree', 'browse', 'json',
                                                  dy_params={'libID': lid, 'view': 'caselib'})
        case_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = case_url
        res = r_session.get(url=cls.zt_base_url, params=prefix_param, headers=headers)
        if res.status_code == 200:
            data = json.loads(json.loads(res.text).get('data')).get('sons')
            zt_first_modules = {d.get('name'): d.get('id') for d in data}
            return zt_first_modules
    
    @classmethod
    def get_zt_user(cls, r_session):
        """获取禅道所有用户
        :return:
        """
        prefix_param = cls._query_params_new('company', 'browse', 'json',
                                              dy_params={'param': 0, 'type': 'bydept',
                                                         'orderBy': 'role_asc', 'recTotal': 103,
                                                         'recPerPage': 1000})
        prefix_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = prefix_url
        res = r_session.get(url=cls.zt_base_url, params=prefix_param, headers=headers)
        if res.status_code == 200:
            user_data = json.loads(json.loads(res.text).get('data')).get('users')
            # 后端开发，测试，前端开发
            base_user_data = [user for user in user_data if
                              user.get('role') in ['dev', 'qa', 'devfornt']]
            return base_user_data
        return None
    
    @classmethod
    def get_all_module_id(cls, lib_id, r_session=None):
        """获取指定用例库下所有模块
        :param lib_id: 用例库id
        :param r_session:
        :return:
        """
        try:
            prefix_param = cls._query_params_new(cls.m, 'browse', cls.t,
                                                  dy_params={'libID': lib_id, 'moduleID': 0})
            module_url = requests.get(cls.zt_base_url, prefix_param).url
            headers = cls.zt_headers
            headers['Referer'] = module_url
            res_module = r_session.get(url=cls.zt_base_url, headers=headers, params=prefix_param)
            if res_module.status_code == 200:
                s_module = json.loads(res_module.text)
                all_module = json.loads(s_module.get('data')).get(cls.res_param.get('module'))
                return all_module
            return {}
        except Exception as e:
            print(str(e))
            return {}
    
    def add_modules(self, r_session, module_name, lib):
        """添加用例库模块
        :return:
        """
        # 拆解模块
        all_modules_name = module_name.split('/')[1:]
        module_id = i = 0
        while True:
            # 获取模块下所有子模块
            all_modules = self.object.get_zt_modules(r_session, lib, module_id)
            if i >= len(all_modules_name):
                return module_id
            # 查询模块是否存在，不存在则添加
            if all_modules.get(all_modules_name[i]) is None:
                # 添加模块
                self.object.add_lib_modules(r_session, all_modules_name[i], lib, module_id)
            else:
                module_id = all_modules.get(all_modules_name[i])
                i += 1
    
    @classmethod
    def add_lib_modules(cls, r_session, name, lib, modules_id=None):
        """添加用例库的模块
        :param r_session:
        :param name: 模块名称
        :param lib: 用例库id
        :param modules_id: 模块id
        :return:
        """
        if modules_id:
            prefix_param = cls._query_params_new('tree', 'manageChild', 'json',
                                                  dy_params={'root': lib, 'viewType': 'caselib',
                                                             'moduleID': modules_id, 'branch': 0})
        else:
            prefix_param = cls._query_params_new('tree', 'manageChild', 'json',
                                                  dy_params={'root': lib, 'viewType': 'caselib'})
        
        add_modules_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = add_modules_url
        
        add_modules_data = {
            'modules[]': name,
            'shorts[]': '',
            'parentModuleID': modules_id
        }
        res = r_session.post(url=cls.zt_base_url, headers=headers, params=prefix_param,
                             data=add_modules_data)
        if res.status_code == 200:
            return res.text
    
    @classmethod
    def get_zt_case_add_front_data(cls, import_type, lib):
        """获取禅道用例添加用例前置数据-用例库-用例
        :return:
        """
        if import_type == '1':
            prefix_param = cls._query_params_new(cls.m, 'createCase', cls.t,
                                                  dy_params={'libID': lib, 'moduleID': 0})
        else:
            prefix_param = cls._query_params_new('testcase', 'create', cls.t,
                                                  dy_params={'productID': lib, 'moduleID': 0,
                                                             'branch': 0})
        case_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = case_url
        return {'prefix_param': prefix_param, 'case_url': case_url, 'headers': headers}
    
    @classmethod
    def new_zt_case_sync(cls, r_session, case_data, zt_data):
        """禅道用例库同步用例-同步
        :return:
        """
        try:
            res_case = r_session.post(url=cls.zt_base_url, data=case_data,
                                      params=zt_data.get('prefix_param'),
                                      headers=zt_data.get('headers'))
            if res_case.status_code == 200:
                if res_case.text.find("alert") != -1:
                    text = res_case.text.split("alert('")[1].split("')\n")[0]
                    case_id = res_case.text.split('caseID=')[1].split('\'')[0]
                    err = {'text: ': text, 'case_id: ': case_id}
                    print(err)
        except Exception as e:
            print(str(e))
    
    @staticmethod
    def handle_colon(content, word):
        """处理冒号
        :param content:
        :param word:
        :return:
        """
        # 英文:
        if content.find('{}:'.format(word)) != -1:
            symbol = ':'
        # 中文：
        elif content.find('{}：'.format(word)) != -1:
            symbol = '：'
        else:
            symbol = ''
        data = content.split('{}{}'.format(word, symbol))[1]
        return data
    
    @classmethod
    def key_word(cls, case_content):
        """处理关键词
        :param case_content:
        :return:
        """
        # 用例库名称或者用例名称
        case_title = case_content.split('-')[0]
        key_word = story = ''
        for filed in case_content.split('-')[1:]:
            if filed.find('关键词') != -1:
                key_word = cls.handle_colon(filed, '关键词')
            if filed.find('需求') != -1:
                story = cls.handle_colon(filed, '需求')
        return case_title, key_word, story


class TypeEnums(Enum):
    OLDTONEW = 0, 'oldtonew'
    LOWBUG = 1, 'lowbug'
    LOWBUGAPI = 2, 'resolve'
    NOLOWBUGAPI = 3, 'nolowbugjk'
    NOLOWBUG = 4, 'nolowbug'
    BUGONLINE = 5, 'bugonline'
    OTHER = 6, 'requirebug'
    
    def __init__(self, b_id, desc):
        self._id = b_id
        self._desc = desc
    
    @property
    def desc(self):
        return self._desc
    
    @property
    def id(self):
        return self._id
